#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author :   Liang Kang
@Contact:   gangkanli1219@163.com
@Time   :   2018/7/31 13:51
@Desc   :
"""
from pathlib import Path
from typing import Iterable

from dltools.utils import log


def check_input_file(func):
    """
    检查文件的存在性
    Parameters
    ----------
    func

    Returns
    -------

    """

    def wrapper(*args, **kwargs):
        filename = kwargs['filename'] or args[0]
        path = Path(filename)
        if path.is_dir():
            raise IsADirectoryError('{} 是一个文件夹！'.format(str(path)))
        if not path.exists():
            raise FileNotFoundError('不存在文件： {}！'.format(str(path)))
        return func(*args, **kwargs)

    return wrapper


def check_output_file(func):
    """
    检查文件的存在性
    Parameters
    ----------
    func

    Returns
    -------

    """

    def wrapper(*args, **kwargs):
        filename = kwargs['filename'] or args[0]
        path = Path(filename)
        if path.is_dir():
            raise IsADirectoryError('{} 是一个文件目录！'.format(str(path)))
        if not path.parent.exists():
            path.parent.mkdir(parents=True)
        return func(*args, **kwargs)

    return wrapper


class BaseIO(object):

    def __init__(self, logger=None, scope='BaseIO'):
        super(BaseIO, self).__init__()
        self._scope_name = scope
        if logger is not None:
            self._logger = logger
        else:
            self._logger = log.get_console_logger(scope)

    def _read(self, *args, **kwargs):
        """
        读取文件
        Parameters
        ----------
        args
        kwargs

        Returns
        -------

        """
        # 文本类文件
        filename = kwargs.get('filename', None) or args[0]
        mode = kwargs.get('mode', None) or 'r'
        self._logger.info('读取文件： {}'.format(filename))
        with open(filename, mode) as file:
            return file.readlines()

    @check_input_file
    def read(self, *args, **kwargs):
        return self._read(*args, **kwargs)

    def _write(self, *args, **kwargs):
        """
        输出文件
        Parameters
        ----------
        args
        kwargs

        Returns
        -------

        """
        # 文本类文件
        filename = kwargs.get('filename', None) or args[0]
        mode = kwargs.get('mode', None) or 'w'
        data = kwargs.get('data', '') or args[1]
        self._logger.info('输出文件： {}'.format(filename))
        with open(filename, mode) as file:
            if isinstance(data, Iterable):
                for _data in data:
                    file.write(_data)
            else:
                file.write(data)

    @check_output_file
    def write(self, *args, **kwargs):
        return self._write(*args, **kwargs)
